package com.story.web.shiro.dao;

import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.web.subject.support.DefaultWebSubjectContext;

import com.story.domain.SessionEntity;
import com.story.domain.SessionInfo;

public class UserSessionDao extends EnterpriseCacheSessionDAO {
	public List<SessionEntity> listActiveSessions(){
		Collection<Session> sessions = getActiveSessions();
		List<SessionEntity> sessionList = new LinkedList<SessionEntity>();
		for(Session session : sessions){
			String jsessionId = session.getId().toString();
			PrincipalCollection principalCollection =  (PrincipalCollection) session.getAttribute(DefaultWebSubjectContext.PRINCIPALS_SESSION_KEY);
			String loginName = null;
			if(principalCollection != null){
				loginName = (String) principalCollection.getPrimaryPrincipal();
			}			
			String loginIp = session.getHost();
			Date startLoginTime = session.getStartTimestamp();
			Date lastAccessTime = session.getLastAccessTime();
			SessionEntity sessionEntity = new SessionEntity();
			sessionEntity.setJsessionId(jsessionId);
			sessionEntity.setLoginName(loginName);
			sessionEntity.setLoginIp(loginIp);
			sessionEntity.setStartLoginTime(startLoginTime);
			sessionEntity.setLastAccessTime(lastAccessTime);
			sessionList.add(sessionEntity);			
		}
		return sessionList;
	}
	
	public List<SessionEntity> listActiveSessionsWithLimit(Integer pageNum,Integer pageSize){
		List<SessionEntity> list = listActiveSessions();
		Integer count = getActiveSessionsCount();
		if(pageNum<1){
			pageNum = 1;
		}
		if(pageSize<10){
			pageSize = 10;
		}
		Integer startIndex = (pageNum - 1) * pageSize;
		Integer toIndex = pageSize * pageNum - 1;
		if(startIndex<0){
			startIndex = 0;
		}
		if(toIndex > count){
			toIndex = count;
		}
		return list.subList(startIndex, toIndex);
	}
	
	public Integer getActiveSessionsCount(){
		return getActiveSessions().size();
	}
}
